package com.sam.springboot.algorithm;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @classname: RoundRobinV0
 * @description: 轮询
 * @Author: sam
 * @date: 2022/5/22 9:00
 */
@Slf4j
public class RoundRobinV0<T> implements Balance<T>{
    private static volatile Integer index = 0;
    @Override
    public  T chooseOne(List<T> list) {
        T t = null;
        synchronized (index){
            if (list==null || list.size()==0){
                index=0;
            }
            int size = list.size();
            int temp = index % size;
            t = list.get(temp);
            index++;
        }
        return t;
    }

    public static void main(String[] args) {
        List<String> services = new ArrayList<>();

        services.add("192.168.0.1");
        services.add("192.168.0.2");
        services.add("192.168.0.3");
        services.add("192.168.0.4");
        services.add("192.168.0.5");

        new Thread(()->{
            RoundRobinV0<String> roundRobin = new RoundRobinV0<String>();
            for (int i=1;i<=5;i++){
                log.info("{}--第{}次获取节点：{}",Thread.currentThread().getName(),i,roundRobin.chooseOne(services));
            }
        }).start();
        new Thread(()->{
            RoundRobinV0<String> roundRobin = new RoundRobinV0<String>();
            for (int i=1;i<=5;i++){
                log.info("{}--第{}次获取节点：{}",Thread.currentThread().getName(),i,roundRobin.chooseOne(services));
            }
        }).start();

        /*RoundRobinV0<String> roundRobinV0 = new RoundRobinV0();
        for (int i=1;i<services.size();i++){
            log.info("{}--第{}次获取节点：{}",Thread.currentThread().getName(),i,roundRobinV0.chooseOne(services));
        }*/
    }
}